//
//  PictureBrowserController.swift
//  XinLangWeibo10
//
//  Created by 白利兵 on 15/11/5.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
// 思路
// 1. 懒加载子控件（collectionView, collectionViewCell, closeButton, SaveButton）
// 2. 通过通知来传递照片的索引和图片的url数组
// 3. 构造函数，传递照片和url数组
let margin: CGFloat = 20
let pictureBrowserCellReuseID = "pictureBrowserCellReuseID"
class PictureBrowserController: UIViewController {
    // MARK: - 属性
    private var currentPicIndexPath: NSIndexPath
    private var picUrls: [NSURL]
    // MARK: - 构造函数
    init(currentPicIndexPath: NSIndexPath, picUrls: NSArray) {
        self.currentPicIndexPath = currentPicIndexPath
        self.picUrls = picUrls as! [NSURL]
        super.init(nibName: nil, bundle: nil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - 生命周期
    override func loadView() {
        view = UIView()
        view.frame = UIScreen.mainScreen().bounds
        view.backgroundColor = UIColor.whiteColor()
        // 设置UI
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 滚动到指定位置
        collectionView.scrollToItemAtIndexPath(currentPicIndexPath, atScrollPosition: .CenteredHorizontally, animated: true)
    }
    // MARK: - 懒加载控件
    private lazy var collectionView: pictureBrowserView = pictureBrowserView()
    // 保存按钮
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 15, color: UIColor.whiteColor(), backImageName: "", backColor: UIColor.darkGrayColor())
    // 关闭按钮
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 15, color: UIColor.whiteColor(), backImageName: "", backColor: UIColor.darkGrayColor())
}
/// MARK: - 设置UI
extension PictureBrowserController {
    private func setupUI() {
        // 添加控件
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        collectionView.dataSource = self
        // 注册监听事件
        saveButton.addTarget(self, action: "savePhotoClick", forControlEvents: .TouchUpInside)
        closeButton.addTarget(self, action: "closeViewClick", forControlEvents: .TouchUpInside)
        // 设置布局
        collectionView.frame = view.bounds
        // saveButon
        saveButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-margin)
            make.left.equalTo(view.snp_left).offset(margin)
            make.size.equalTo(CGSize(width: 80, height: 32))
        }
        // closeButton
        closeButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(saveButton.snp_bottom)
            make.right.equalTo(view.snp_right).offset(-margin)
            make.size.equalTo(CGSize(width: 80, height: 32))
        }
    }
    @objc func close() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func savePhotoClick() {
        // 保存图片
        print("保存图片")
        // 获取当前的图片
        guard let image = (collectionView.visibleCells().last as? PictureBrowserViewCell)?.imageView.image else {
            print("没有图像")
            return
        }
        UIImageWriteToSavedPhotosAlbum(image, self, nil, nil)
    }
    @objc private func closeViewClick() {
        // 控制器跳转
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}

/// MARK: - 自定义collectionView
class pictureBrowserView: UICollectionView {
    var picIndexPath: NSIndexPath?
    var picUrls: [NSURL]?
    // 构造方法
    init() {
        // 创建流式布局
        let flowLayout = UICollectionViewFlowLayout()
        // 设置布局属性
        flowLayout.itemSize = CGSizeMake(ScreenWidth, ScreenHeight)
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        flowLayout.scrollDirection = .Horizontal
        // 初始化父类
        super.init(frame: UIScreen.mainScreen().bounds, collectionViewLayout: flowLayout)
        // 展示分页效果
        pagingEnabled = true
        // 关闭弹簧效果
        bounces = false
        // 注册可重用cell
        registerClass(PictureBrowserViewCell.self, forCellWithReuseIdentifier: pictureBrowserCellReuseID)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
/// MARK: - 数据源方法
extension PictureBrowserController: UICollectionViewDataSource {
    // 返回多少项
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return picUrls.count ?? 0
    }
    
    // 返回怎样的cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        // 从可重用缓存池中取cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureBrowserCellReuseID, forIndexPath: indexPath) as! PictureBrowserViewCell
        // 设置图片数据
        cell.url = picUrls[indexPath.item]
        cell.delegate = self
        // 设置代理
        return cell
    }
}
/// MARK: - PictureBrowserViewCellDelegate代理方法
extension PictureBrowserController: PictureBrowserViewCellDelegate {
    func PictureBrowserViewCellDidSelected(cell: UICollectionViewCell) {
        close()
    }
}

extension PictureBrowserController: PictureAnimatorDismissDelegate {
    // 源图片的frame
    /// 解除转场动画的图像视图
    func imageViewForDismiss() -> UIImageView {
        let cell = collectionView.visibleCells()[0] as! PictureBrowserViewCell
        let iv = cell.imageView
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        // 获取frame
        iv.frame = cell.scrollView.convertRect(cell.imageView.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return iv
    }
    /// 解除转场动画的图像索引
    func indexPathForDismiss() -> NSIndexPath {
        return collectionView.indexPathsForVisibleItems()[0]
    }
}





















